//
//  HRZAdVertiseView.m
//  EMarket
//
//  Created by 石头 on 2018/11/27.
//  Copyright © 2018 好日子. All rights reserved.
//

#import "HRZAdVertiseView.h"

@interface HRZAdVertiseView ()

@property (nonatomic, strong) UIImageView *adView;

@property (nonatomic, strong) UIButton *countBtn;

@property (nonatomic, strong) NSTimer *countTimer;

@property (nonatomic, assign) int count;

@end

static int const showTime = 3;

@implementation HRZAdVertiseView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    if (self) {
        
        [self addSubview:self.adView];
        
        [self addSubview:self.countBtn];
    }
    
    return self;
}

#pragma mark - ----  method  ----
- (void)show {
    
    // 倒计时方法1:GCD
//    [self startCoundown];
    
    // 倒计时方法2:定时器
    [self startTimer];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
}

- (void)setFilePath:(NSString *)filePath {
    _filePath = filePath;
    self.adView.image = [UIImage imageWithContentsOfFile:filePath];
}


#pragma mark - ----  Method  ----

- (void)pushToAd {
    [self dismiss];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:PUSHTOAD object:nil];
}

- (void)countDown {
    _count --;
    [self.countBtn setTitle:[self dismissTimeString:_count] forState:UIControlStateNormal];
    if (_count == 0) {
        [self dismiss];
    }
}

// 定时器倒计时
- (void)startTimer {
    _count = showTime;
    [[NSRunLoop mainRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];
}

// GCD倒计时
- (void)startCoundown {
    __block int timeout = showTime + 1;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeout <= 0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self dismiss];
                
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.countBtn setTitle:[self dismissTimeString:timeout] forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

/** 移除广告 */
- (void)dismiss {
    [_countTimer invalidate];
    _countTimer = nil;
    
    [UIView animateWithDuration:0.3f animations:^{
        
        self.alpha = 0.f;
        
    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
        
    }];
}

- (NSString *)dismissTimeString:(int)count {
    NSString *str = [NSString stringWithFormat:@"跳过%d", count];
    return str;
}

#pragma mark - ----  Lay  ----
- (UIImageView *)adView{
    if (!_adView) {
        CGRect frame = self.bounds;
        _adView = [[UIImageView alloc] initWithFrame:frame];
        _adView.userInteractionEnabled = YES;
        _adView.contentMode = UIViewContentModeScaleAspectFill;
        _adView.clipsToBounds = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushToAd)];
        [_adView addGestureRecognizer:tap];
    }
    return _adView;
}

- (UIButton *)countBtn{
    if (!_countBtn) {
        CGFloat btnW = 60;
        CGFloat btnH = 30;
        _countBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - btnW - 24, btnH, btnW, btnH)];
        [_countBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        [_countBtn setTitle:[self dismissTimeString:showTime] forState:UIControlStateNormal];
        _countBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_countBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _countBtn.backgroundColor = JumpAdBtnBgColor;
        _countBtn.layer.cornerRadius = 4;
    }
    return _countBtn;
}

- (NSTimer *)countTimer{
    if (!_countTimer) {
        _countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    }
    return _countTimer;
}

@end
